package com.ias.agdis_r.manager;

import android.os.HandlerThread;
import android.os.Message;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * TTS语音排队播报
 * Created by zhaowl on 2017/10/10.
 */
public class TTSMessageTask {

    private static volatile TTSMessageTask manager;
    private final List<String> listMessage = new LinkedList<>();
    private android.os.Handler handler;
    private static final int MESSAGE_WHAT = 1;      // 消息code

    public List<String> getListMessage() {
        return listMessage;
    }

    public static TTSMessageTask getInstance() {
        if (manager == null) {
            synchronized (TTSMessageTask.class) {
                if (manager == null) {
                    manager = new TTSMessageTask();
                }
            }
        }
        return manager;
    }

    private TTSMessageTask() {
        HandlerThread handlerThread = new HandlerThread("tts_message_task_handler");
        handlerThread.start();
        handler = new android.os.Handler(handlerThread.getLooper(), new android.os.Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                synchronized (listMessage) {
                    Iterator<String > iterator = listMessage.iterator();
                    if (iterator.hasNext()) {
                        String next = iterator.next();
                        TTSManager.getInstance().ttsPlayReally(next);
                    }
                }
                return false;
            }
        });
    }

    /** 通知任务 */
    public void notifyTTS() {
        handler.sendEmptyMessage(MESSAGE_WHAT);
    }

    /**
     * 消息加入检测任务
     * @param message
     */
    public void addMessage(String message) {
        boolean state = listMessage.isEmpty();
        listMessage.add(message);
        if (state) {
            notifyTTS();
        }
    }

    public void closeMessage() {
        listMessage.clear();
        TTSManager.getInstance().ttsCancelReally();
    }

}
